//
//  MyGoodsSureOrderViewModel.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/4/9.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "MyGoodsSureOrderViewModel.h"
//unitls
#import "Global.h"
#import "NSString+Conversion.h"
#import "ManagerHttpBase.h"
#import "ManagerGlobeUntil.h"
//vendor
#import "FMDBManager.h"
//model
#import "ReceivedAddressModel.h"

#define ktopSpace 12
#define ksepLineHight 0.5
typedef void (^MyGoodsSureOrderRequestFinished) (BOOL isRequestFinished);
@interface MyGoodsSureOrderViewModel ()
@property(nonatomic,weak)MyGoodsSureOrderRequestFinished isRequestFinished;
@end
@implementation MyGoodsSureOrderViewModel
- (id)init {
    self = [super init];
    if (self) {
        [self resetDatas];
    }
    return self;
}

- (void)resetDatas {
    _dataSource = [[NSMutableArray alloc]init];
    self.storeGoodsCount = @"";
    self.storeGoodsID = @"";
    self.selfGoodsCount = @"";
    self.selfGoodsID = @"";
    self.totalPrice = @"";
    self.storeGoodsPrice = @"";
    self.selfGoodsPrice = @"";
    self.offsetTotalPrice =@"";
    self.offsetStoreGoodsPrice =@"";
    self.offsetSelfGoodsPrice =@"";
}
- (void)requestDatasSuccess:(void(^)(BOOL isSuccess))successs failure:(void(^)(NSString*failureInfo))failureInfo {
    
    [self loadUserShiHuiBiNumberSuccess:successs failure:failureInfo];
}

//获取默认收货地址信息
- (void)loadDefaultReceivedAddressDataSuccess:(void(^)(BOOL isSuccess))successs failure:(void(^)(NSString*failureInfo))failureInfo {
    NSMutableArray *receivedAddressArr = [[NSMutableArray alloc]init];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    UserInfoModel *model = [[ManagerGlobeUntil sharedManager] getUserInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:model.token forKey:@"TOKEN"];
    [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"user/defaultAddress" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            ReceivedAddressModel *model = [ReceivedAddressModel modelObjectWithDictionary:responseObject];
            NSString *state = [NSString stringTransformObject:model.sTATE];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                if (model.oBJECT.count != 0) {
                    [receivedAddressArr addObjectsFromArray:model.oBJECT];
                    [weakSelf calculationTableHeaderHightWithAddressStatus:YES];
                    weakSelf.isHadRecivedAddress = YES;
                    weakSelf.receivedAddressInfo = [receivedAddressArr firstObject];
                
                } else {
                    [weakSelf calculationTableHeaderHightWithAddressStatus:NO];
                }
                
            }else {//请求失败
                 weakSelf.isHadRecivedAddress = NO;
                [weakSelf calculationTableHeaderHightWithAddressStatus:NO];
            }
            weakSelf.isRequestFinished = successs;
            [weakSelf configureGoodsData];
        }
    } failure:^(bool isFailure) {
         weakSelf.isHadRecivedAddress = NO;
        [weakSelf calculationTableHeaderHightWithAddressStatus:NO];
         failureInfo(@"数据异常");
    }];
}
-(void)loadUserShiHuiBiNumberSuccess:(void(^)(BOOL isSuccess))successs failure:(void(^)(NSString*failureInfo))failureInfo{
    ManagerHttpBase *manager=[ManagerHttpBase sharedManager];
        UserInfoModel *model = [[ManagerGlobeUntil sharedManager] getUserInfo];
        NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
        [parameter setObject:model.token forKey:@"TOKEN"];
        __weak typeof(self)weakSelf = self;
        [manager parameters:parameter customPOST:@"user/money" success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dataDic = (NSDictionary*)responseObject;
                NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
                if ([state isEqualToString:@"0"]) {//请求成功
                    NSDictionary *dic=[dataDic objectForKey:@"OBJECT"];
                  weakSelf.shiHuiBiMoney = [NSString marketLastTwoByteOfStringIsZero:[NSString stringWithFormat:@"%.2f",[[NSString stringTransformObject:[dic objectForKey:@"MONEY"]] floatValue]]];
                    [self loadDefaultReceivedAddressDataSuccess:successs failure:failureInfo];
                } else {
                }
            }
        } failure:^(bool isFailure) {
        }];
}
//对商品数据进行处理
- (void)configureGoodsData {
    CGFloat totalGoodsPrice = 0;
    CGFloat storeGoodsTotalPrice = 0;
    CGFloat selfGoodsTotalPrice = 0;
    CGFloat offtotalGoodsPrice = 0;
    CGFloat offstoreGoodsTotalPrice = 0;
    CGFloat offselfGoodsTotalPrice = 0;
    [self.dataSource removeAllObjects];
    NSMutableArray *storeGoodsIDArr = [[NSMutableArray alloc]init];//便利店商品ID
    NSMutableArray *selfGoodsIDArr = [[NSMutableArray alloc]init];//自营商品ID
    NSMutableArray *storeGoodsNumberArr = [[NSMutableArray alloc]init];//便利店商品个数
    NSMutableArray *selfGoodsNumberArr = [[NSMutableArray alloc]init];//自营商品个数
    //计算便利店商品价格
    if (self.storeGoodsArr.count != 0) {
        for (NSDictionary *dataDic in self.storeGoodsArr) {
            storeGoodsTotalPrice +=[[dataDic objectForKey:@"SELLPRICE"] floatValue]*[[dataDic objectForKey:@"BUYNUM"] integerValue];
            [storeGoodsIDArr addObject:[dataDic objectForKey:@"ID"]];
            [storeGoodsNumberArr addObject:[dataDic objectForKey:@"BUYNUM"]];
        }
        self.storeGoodsID = [storeGoodsIDArr componentsJoinedByString:@","];
        self.storeGoodsCount = [storeGoodsNumberArr componentsJoinedByString:@","];
        self.storeGoodsPrice = [NSString stringWithFormat:@"%.2f",storeGoodsTotalPrice];
        offstoreGoodsTotalPrice = storeGoodsTotalPrice-self.shiHuiBiMoney.floatValue;
        if (offstoreGoodsTotalPrice <=0) {
            offstoreGoodsTotalPrice = 0;
        }
        self.offsetStoreGoodsPrice = [NSString stringWithFormat:@"%.2f",offstoreGoodsTotalPrice];
        //插入便利店商品价格
        [self.storeGoodsArr addObject:@{@"title":@"总计",@"content":self.storeGoodsPrice}];
        [self.dataSource addObject:self.storeGoodsArr];
    }
    //计算自营商品价格
    if (self.selfGoodsArr.count != 0) {
        for (NSDictionary *dataDic in self.selfGoodsArr) {
            selfGoodsTotalPrice +=[[dataDic objectForKey:@"SELLPRICE"] floatValue]*[[dataDic objectForKey:@"BUYNUM"] integerValue];
            [selfGoodsIDArr addObject:[dataDic objectForKey:@"ID"]];
            [selfGoodsNumberArr addObject:[dataDic objectForKey:@"BUYNUM"]];
        }
        self.selfGoodsID = [selfGoodsIDArr componentsJoinedByString:@","];
        self.selfGoodsCount = [selfGoodsNumberArr componentsJoinedByString:@","];
        self.selfGoodsPrice = [NSString stringWithFormat:@"%.2f",selfGoodsTotalPrice];
        offselfGoodsTotalPrice = selfGoodsTotalPrice-self.shiHuiBiMoney.floatValue;
        if (offselfGoodsTotalPrice <=0) {
            offselfGoodsTotalPrice = 0;
        }
        self.offsetSelfGoodsPrice = [NSString stringWithFormat:@"%.2f",offselfGoodsTotalPrice];
        //对自营商品数据进行处理(把固定数据插到真实数据前部)
        [self.selfGoodsArr insertObject:@{@"title":kDaShiHuiStoreName,@"content":@"在线支付+第三方配送"} atIndex:0];
        //插入自营商品价格
        [self.selfGoodsArr addObject:@{@"title":@"总计",@"content":self.selfGoodsPrice}];
        [self.dataSource addObject:self.selfGoodsArr];
    }
    //计算商品总价格
    totalGoodsPrice = storeGoodsTotalPrice + selfGoodsTotalPrice;
    
    self.totalPrice = [NSString stringWithFormat:@"%.2f",totalGoodsPrice];
    offtotalGoodsPrice = totalGoodsPrice-self.shiHuiBiMoney.floatValue;
    if (offtotalGoodsPrice <=0) {
        offtotalGoodsPrice = 0;
    }
    self.offsetTotalPrice = [NSString stringWithFormat:@"%.2f",offtotalGoodsPrice];
    self.isRequestFinished(YES);
    
}
- (void)calculationTableHeaderHightWithAddressStatus:(BOOL)isHadAddress {
    if (self.storeGoodsArr.count != 0) {//便利店商品不为0，table头部包含支付方式等待
        if (isHadAddress) {
            self.tableHeaderHight = 2*ktopSpace + 4*ksepLineHight + HightScalar(88 + 47*3);
        } else {
            self.tableHeaderHight = 2*ktopSpace + 7*ksepLineHight + HightScalar(47*7);
        }
    } else {//只包含自营商品
        if (isHadAddress) {
            self.tableHeaderHight = 2*ktopSpace + HightScalar(88);
        } else {
            self.tableHeaderHight = 2*ktopSpace + 5*ksepLineHight + HightScalar(47*4);
        }
    }
    
}
- (CGFloat)tableFooterHight {
    return ktopSpace + 2*ksepLineHight + HightScalar(47) + 58;
}

- (NSInteger)selectdGoodsType {
    if (self.storeGoodsArr.count != 0 && self.selfGoodsArr.count != 0) {//包含自营和便利店商品
        return 2;
    } else if (self.storeGoodsArr.count != 0 && self.selfGoodsArr.count == 0) {//只包含便利店商品
        return 0;
    } else {//只包含自营商品
        return 1;
    }
}
@end
